package com.c6chapter6;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class ContextServletTest extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletContext context = this.getServletContext();
        InputStream stream = context.getResourceAsStream("/WEB-INF/classes/jdbc.properties");
        Properties properties = new Properties();
        properties.load(stream);
        String dbName = properties.getProperty("dbName");
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        url = url+dbName+"?username="+username+"&password="+password;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection(url);
            Statement stmt = conn.createStatement();
            String sql = "select * from student_db100 ORDER BY id DESC,number DESC";
            ResultSet rs = stmt.executeQuery(sql);
            out.println("<table border=1>");
            out.println("<th colspan=4 style='font-size:x-large;align:center'>学生信息表</th>");
            out.println("<tr style='align:center'>");
            out.println("<td>学号</td> <td>姓名</td> <td>出生日期</td> <td>所在班级</td>");
            while(rs.next()){
                out.println("<tr style='align:center'>");
                out.println("<td>"+rs.getString("id")+"</td>");
                out.println("<td>"+rs.getString("name")+"</td>");
                out.println("<td>"+rs.getString("birthday")+"</td>");
                out.println("<td>"+rs.getString("class")+"</td>");
                out.println("</tr>");
            }
            out.println("</table></body>");
        }catch (Exception e){
            e.printStackTrace();
        }
        out.flush();
        out.close();
    }
}